package com.healthyeating.manage.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.healthyeating.common.core.domain.entity.SysUser;
import com.healthyeating.common.exception.ServiceException;
import com.healthyeating.common.utils.DateUtils;
import com.healthyeating.common.utils.SecurityUtils;
import com.healthyeating.common.utils.ServletUtils;
import com.healthyeating.common.utils.ip.AddressUtils;
import com.healthyeating.common.utils.ip.IpUtils;
import com.healthyeating.manage.domain.Comment;
import com.healthyeating.manage.domain.RecipeComment;
import com.healthyeating.manage.domain.UserComment;
import com.healthyeating.manage.domain.vo.CommentVo;
import com.healthyeating.manage.domain.vo.RecipeCommentVo;
import com.healthyeating.manage.mapper.CommentMapper;
import com.healthyeating.manage.mapper.RecipeCommentMapper;
import com.healthyeating.manage.service.ICommentService;
import com.healthyeating.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 评论Service业务层处理
 *
 * @author 段奇乐
 * @date 2025-03-26
 */
@Service
public class CommentServiceImpl implements ICommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private RecipeCommentMapper recipeCommentMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 查询评论列表
     *
     * @param shareId 发现分享id
     * @return 评论列表集合
     */
    @Override
    public List<CommentVo> selectCommentListByShareId(Long shareId) {
        // 查询所有属于该 shareId 的一级评论
        List<Comment> firstCommentList = commentMapper.selectFirstCommentListByShareId(shareId);
        List<CommentVo> firstCommentVoList = firstCommentList.stream().map(comment -> {
            // 补充vo信息
            CommentVo commentVo = new CommentVo();
            SysUser user = sysUserMapper.selectUserById(comment.getUserId());
            BeanUtil.copyProperties(comment, commentVo);
            commentVo.setAvatar(user.getAvatar());
            commentVo.setUserName(user.getUserName());
            // 查找子评论
            Map<String, Object> map = new HashMap<>();
            map.put("shareId", comment.getShareId());
            map.put("topId", comment.getCommentId());
            List<Comment> secondCommentList = commentMapper.selectSecondCommentList(map);
            List<CommentVo> secondCommentVoList = secondCommentList.stream().map(secondComment -> {
                CommentVo secondCommentVo = new CommentVo();
                BeanUtil.copyProperties(secondComment, secondCommentVo);
                // 补充vo信息
                SysUser secondUser = sysUserMapper.selectUserById(secondComment.getUserId());
                secondCommentVo.setAvatar(secondUser.getAvatar());
                secondCommentVo.setUserName(secondUser.getUserName());
                if (secondComment.getToUserId() != null) {
                    SysUser toUser = sysUserMapper.selectUserById(secondComment.getToUserId());
                    secondCommentVo.setToUserName(toUser.getUserName());
                }
                // 查询评论点赞记录
                UserComment userComment_ = commentMapper.selectUserCommentByCommentIdAndUserId(secondComment.getCommentId(), SecurityUtils.getUserId());
                if (userComment_ != null) {
                    secondCommentVo.setLikeFlag(userComment_.getLikeFlag());
                } else {
                    secondCommentVo.setLikeFlag(0);
                }
                return secondCommentVo;
            }).collect(Collectors.toList());
            commentVo.setCommentChildList(secondCommentVoList);
            // 查询评论点赞记录
            UserComment userComment = commentMapper.selectUserCommentByCommentIdAndUserId(comment.getCommentId(), SecurityUtils.getUserId());
            if (userComment != null) {
                commentVo.setLikeFlag(userComment.getLikeFlag());
            } else {
                commentVo.setLikeFlag(0);
            }
            return commentVo;
        }).collect(Collectors.toList());
        return firstCommentVoList;
    }

    /**
     * 新增评论
     *
     * @param comment 评论
     * @return 结果
     */
    @Override
    @Transactional
    public int insertComment(Comment comment, HttpServletRequest request) {
        Comment _comment = new Comment();
        // 评论id不为空，则为回复
        if (comment.getCommentId() != null) {
            if (Objects.equals(comment.getUserId(), SecurityUtils.getUserId())) {
                throw new ServiceException("不能回复自己的评论");
            }
            // 判断是回复一级还是回复二级评论
            if (comment.getParentId() == null && comment.getTopId() == null) {
                // 回复一级评论
                _comment.setParentId(comment.getCommentId());
                _comment.setTopId(comment.getCommentId());
            } else {
                // 回复二级评论
                _comment.setParentId(comment.getCommentId());
                _comment.setTopId(comment.getTopId());

            }
            _comment.setShareId(comment.getShareId());
            _comment.setCommentBody(comment.getCommentBody());
            _comment.setToUserId(comment.getUserId());
        } else {
            // 评论id为空，则为一级评论
            _comment.setShareId(comment.getShareId());
            _comment.setCommentBody(comment.getCommentBody());
        }
        _comment.setUserId(SecurityUtils.getUserId());
        _comment.setCreateTime(DateUtils.getNowDate());
        _comment.setIpAddr(AddressUtils.getRealAddressByIP(IpUtils.getIpAddr(request)));
        _comment.setLikeNum(0);
        int result = commentMapper.insertComment(_comment);
        // 新增点赞记录（未点赞）
        UserComment userComment = new UserComment();
        userComment.setUserId(SecurityUtils.getUserId());
        userComment.setCommentId(_comment.getCommentId());
        userComment.setLikeFlag(0);
        commentMapper.insertUserComment(userComment);
        return result;
    }

    /**
     * 修改评论
     *
     * @param commentVo 评论
     * @return 结果
     */
    @Override
    @Transactional
    public int updateComment(CommentVo commentVo) {
        UserComment userComment = commentMapper.selectUserCommentByCommentIdAndUserId(commentVo.getCommentId(), SecurityUtils.getUserId());
        if (userComment == null) {
            UserComment _userComment = new UserComment();
            _userComment.setUserId(SecurityUtils.getUserId());
            _userComment.setCommentId(commentVo.getCommentId());
            _userComment.setLikeFlag(1);
            commentMapper.insertUserComment(_userComment);
        } else {
            userComment.setLikeFlag( commentVo.getLikeFlag() == 1 ? 0 : 1);
            commentMapper.updateUserComment(userComment);
        }
        return commentMapper.updateComment(commentVo);
    }

    /**
     * 查询食谱评论列表
     *
     * @param recipeId 食谱id
     * @return 评论列表集合
     */
    @Override
    public List<RecipeCommentVo> selectCommentListByRecipeId(Long recipeId) {
        // 查询所有属于该 recipeId 的一级评论
        List<RecipeComment> firstCommentList = recipeCommentMapper.selectFirstCommentListByRecipeId(recipeId);
        List<RecipeCommentVo> firstCommentVoList = firstCommentList.stream().map(comment -> {
            // 补充vo信息
            RecipeCommentVo commentVo = new RecipeCommentVo();
            SysUser user = sysUserMapper.selectUserById(comment.getUserId());
            BeanUtil.copyProperties(comment, commentVo);
            commentVo.setAvatar(user.getAvatar());
            commentVo.setUserName(user.getUserName());
            // 查找子评论
            Map<String, Object> map = new HashMap<>();
            map.put("recipeId", comment.getRecipeId());
            map.put("topId", comment.getCommentId());
            List<RecipeComment> secondCommentList = recipeCommentMapper.selectSecondCommentList(map);
            List<RecipeCommentVo> secondCommentVoList = secondCommentList.stream().map(secondComment -> {
                RecipeCommentVo secondCommentVo = new RecipeCommentVo();
                BeanUtil.copyProperties(secondComment, secondCommentVo);
                // 补充vo信息
                SysUser secondUser = sysUserMapper.selectUserById(secondComment.getUserId());
                secondCommentVo.setAvatar(secondUser.getAvatar());
                secondCommentVo.setUserName(secondUser.getUserName());
                if (secondComment.getToUserId() != null) {
                    SysUser toUser = sysUserMapper.selectUserById(secondComment.getToUserId());
                    secondCommentVo.setToUserName(toUser.getUserName());
                }
                return secondCommentVo;
            }).collect(Collectors.toList());
            commentVo.setCommentChildList(secondCommentVoList);
            return commentVo;
        }).collect(Collectors.toList());
        return firstCommentVoList;
    }

    /**
     * 新增食谱评论
     *
     * @param comment 评论
     * @return 结果
     */
    @Override
    public int insertRecipeComment(RecipeComment comment, HttpServletRequest request) {
        RecipeComment _comment = new RecipeComment();
        // 评论id不为空，则为回复
        if (comment.getCommentId() != null) {
            if (Objects.equals(comment.getUserId(), SecurityUtils.getUserId())) {
                throw new ServiceException("不能回复自己的评论");
            }
            // 判断是回复一级还是回复二级评论
            if (comment.getParentId() == null && comment.getTopId() == null) {
                // 回复一级评论
                _comment.setParentId(comment.getCommentId());
                _comment.setTopId(comment.getCommentId());
            } else {
                // 回复二级评论
                _comment.setParentId(comment.getCommentId());
                _comment.setTopId(comment.getTopId());

            }
            _comment.setRecipeId(comment.getRecipeId());
            _comment.setCommentBody(comment.getCommentBody());
            _comment.setToUserId(comment.getUserId());
        } else {
            // 评论id为空，则为一级评论
            _comment.setRecipeId(comment.getRecipeId());
            _comment.setCommentBody(comment.getCommentBody());
        }
        _comment.setUserId(SecurityUtils.getUserId());
        _comment.setCreateTime(DateUtils.getNowDate());
        _comment.setIpAddr(AddressUtils.getRealAddressByIP(IpUtils.getIpAddr(ServletUtils.getRequest())));
        return recipeCommentMapper.insertComment(_comment);
    }
}
